const express = require("express");
const router = express.Router();
const fs = require("fs");
const multer = require("multer");
var upload = multer({
  dest: "./uploads/imgs",
});
const mdb = require("../mongodb/db");

router.get("/imgs/:id", (req, res) => {
  mdb.find_img(req.params.id).then((docs) => {
    res.status(200).send(docs);
  });
});

router.post("/upload", upload.any(), function (req, res, next) {
  var filename = `file_${Date.now()}_${req.files[0].fieldname}.png`;
  fs.rename(req.files[0].path, "./uploads/imgs/" + filename, function (err) {
    if (err) {
      throw err;
    }
    mdb
      .upload_img({ id: req.files[0].fieldname, filename: filename })
      .then(() => {
        res.json({ status: 200, msg: { type: "ok", msg: "文件上传成功！" } });
        console.log("文件上传成功！");
      });
  });
});

module.exports = router;
